const tef6686_server = 'http://192.168.0.114'
const tuner =(()=>{
    const writeBuffer = (buf) => {
        return fetch(`${tef6686_server}/write`, {
            method: 'post',
            body: buf.join(',')
        })
    }
    const readBuffer = (len) => {
        return fetch(`${tef6686_server}/read`, {
            method: 'post',
            body: len + ''
        }).then(r => r.text())
    }
    
    const waitMs = (ms) => {
        return new Promise(resolve => {
            setTimeout(resolve, ms)
        })
    }
    
    const chunk = (list, size) => {
        const rst = []
        for (let i = 0; i < list.length; i++) {
            if (i % size == 0) {
                rst.push([])
            }
            rst[rst.length - 1].push(list[i])
        }
        return rst
    }
    
    const patchLoad = async (pLutBytes) => {
        const list = chunk(pLutBytes, 24)
        for (let i = 0; i < list.length; i++) {
            const patch = list[i]
            await Tuner_WriteBuffer([0x1b, ...patch])
        }
    }
    
    const tableWrite = async (tab) => {
        for (let i = 0; i < tab.length; i++) {
            const item = tab[i]
            await tuner[item.method](item.data)
        }
    }
    
    return {
        writeBuffer,
        readBuffer,
        waitMs,
        patchLoad,
        tableWrite,
    }
})()

